﻿using Barrage.Controls;
using BarrageGameAssistant.Core.Enums;
using BarrageGameAssistant.Core.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BarrageGameAssistant.Controls
{
    public class ScriptsListView : ListViewEx
    {
        private readonly ContextMenuStrip rightClickMenu;

        /// <summary>
        /// 描述
        /// </summary>
        [Description("描述")]
        public string? Description { get; set; }

        /// <summary>
        /// 分组
        /// </summary>
        [Description("分组")]
        public string? Group { get; set; }

        /// <summary>
        /// 话术脚本集合数据
        /// </summary>
        [Description("话术脚本集合数据")]
        public List<LanguageScript>? Scripts { get; private set; }

        /// <summary>
        /// 当前游戏场景ID
        /// </summary>
        [Description("当前游戏场景ID")]
        public string? SceneId { get; set; } = null;

        /// <summary>
        /// 数据改变事件
        /// </summary>
        public event EventHandler? DataChanged;

        public ScriptsListView() : base()
        {
            #region 右键菜单
            rightClickMenu = new ContextMenuStrip
            {
                Font = this.Font
            };

            ToolStripMenuItem addItem = new()
            {
                Text = "添加话术"
            };
            addItem.Click += AddItem_Click;
            rightClickMenu.Items.Add(addItem);

            //ToolStripMenuItem editItem = new()
            //{
            //    Text = "编辑话术"
            //};
            //editItem.Click += EditItem_Click;
            //rightClickMenu.Items.Add(editItem);

            ToolStripMenuItem addItemByDir = new()
            {
                Text = "从目录导入"
            };
            addItemByDir.Click += AddItemByDir_Click; ;
            rightClickMenu.Items.Add(addItemByDir);

            ToolStripSeparator toolStripSeparator = new ToolStripSeparator();
            rightClickMenu.Items.Add(toolStripSeparator);

            ToolStripMenuItem delItems = new()
            {
                Text = "删除选中话术"
            };
            delItems.Click += DelItems_Click;
            rightClickMenu.Items.Add(delItems);

            ToolStripSeparator toolStripSeparator1 = new ToolStripSeparator();
            rightClickMenu.Items.Add(toolStripSeparator1);

            ToolStripMenuItem clearItems = new()
            {
                Text = "清空话术"
            };
            clearItems.Click += ClearItems_Click;
            rightClickMenu.Items.Add(clearItems);

            ContextMenuStrip = rightClickMenu;
            #endregion

            #region 设置列
            var headerId = new ColumnHeader
            {
                Name = "Id",
                Text = "序号",
                TextAlign = HorizontalAlignment.Left,
                Width = 80
            };
            Columns.Add(headerId);

            var headerLanguageScriptItemType = new ColumnHeader
            {
                Name = "LanguageScriptItemType",
                Text = "话术类型",
                TextAlign = HorizontalAlignment.Center,
                Width = 120
            };
            Columns.Add(headerLanguageScriptItemType);

            var headerStatus = new ColumnHeader
            {
                Name = "Status ",
                Text = "状态",
                TextAlign = HorizontalAlignment.Center,
                Width = 120
            };
            Columns.Add(headerStatus);

            var headerContent = new ColumnHeader
            {
                Name = "Content",
                Text = "内容",
                TextAlign = HorizontalAlignment.Left,
                Width = 500
            };
            Columns.Add(headerContent);
            #endregion

            this.ShowItemToolTips = true;
            
        }

        protected override void OnAutoSizeChanged(EventArgs e)
        {
            this.Columns[3].Width = -2;
            this.Columns[3].Width -= 10;
            base.OnAutoSizeChanged(e);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public void SetData(List<LanguageScript> data)
        {
            this.Scripts = data ?? throw new ArgumentNullException(nameof(data));

            this.Items.Clear();
            foreach (var item in this.Scripts)
            {
                ListViewItem lvi = this.Items.Add((this.Items.Count + 1).ToString());
                lvi.Tag = item;
                lvi.SubItems.Add(item.Type == LanguageScriptType.Audio ? "音频文件" : "合成语音");
                lvi.SubItems.Add(item.Status == 0 ? "正常" : "禁用");
                lvi.SubItems.Add(item.Content);
            }
        }

        public List<LanguageScript> GetData()
        {
            if (this.Scripts != null)
                return this.Scripts;
            else
            {
                return [];
            }
        }

        private void AddItem_Click(object? sender, EventArgs e)
        {
            if (this.Scripts == null)
            {
                if (string.IsNullOrEmpty(Description))
                    MessageBox.Show(this, $"请先设置话术集数据.", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                    MessageBox.Show(this, $"请先设置【{Description}】的话术集.", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (string.IsNullOrEmpty(Description))
                openFileDialog.Title = $"选择话术音频文件";
            else
                openFileDialog.Title = $"选择{Description}音频文件";
            openFileDialog.Multiselect = true;
            openFileDialog.Filter = "Mp3音频(*.mp3)|*.mp3|Wave音频(*.wav)|*.wav";
            //openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                foreach (var file in openFileDialog.FileNames)
                {
                    LanguageScript script = new LanguageScript();
                    script.Type = LanguageScriptType.Audio;
                    script.Content = file;
                    script.Status = 0;

                    this.Scripts?.Add(script);
                    ListViewItem lvi = this.Items.Add((this.Items.Count + 1).ToString());
                    lvi.Tag = script;
                    lvi.SubItems.Add(script.Type == LanguageScriptType.Audio ? "音频文件" : "合成语音");
                    lvi.SubItems.Add(script.Status == 0 ? "正常" : "禁用");
                    lvi.SubItems.Add(script.Content);
                    DataChanged?.Invoke(this, EventArgs.Empty);
                }
            }

            //FrmLanguageScriptEdit frmLanguageScriptEdit = new()
            //{
            //    Text = $"添加话术",
            //    Owner = this.FindForm(),
            //    Script = null
            //};

            //if (frmLanguageScriptEdit.ShowDialog() == DialogResult.OK)
            //{
            //    if (frmLanguageScriptEdit.Script != null)
            //    {
            //        frmLanguageScriptEdit.Script.Description = this.Description;

            //        this.Scripts?.Add(frmLanguageScriptEdit.Script);
            //        ListViewItem lvi = this.Items.Add((this.Items.Count + 1).ToString());
            //        lvi.Tag = frmLanguageScriptEdit.Script;
            //        lvi.SubItems.Add(frmLanguageScriptEdit.Script.Type == LanguageScriptType.Audio ? "音频文件" : "合成语音");
            //        lvi.SubItems.Add(frmLanguageScriptEdit.Script.Status == 0 ? "正常" : "禁用");
            //        lvi.SubItems.Add(frmLanguageScriptEdit.Script.Content);
            //        DataChanged?.Invoke(this, EventArgs.Empty);
            //    }
            //}
        }

        private void EditItem_Click(object? sender, EventArgs e)
        {
            if (this.SelectedItems.Count < 1) return;

            if (this.Scripts == null)
            {
                if (string.IsNullOrEmpty(Description))
                    MessageBox.Show(this, $"请先设置话术集数据.", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                    MessageBox.Show(this, $"请先设置【{Description}】的话术集.", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ListViewItem item = this.SelectedItems[0];
            if (item == null || item.Tag == null) return;

            FrmLanguageScriptEdit frmLanguageScriptEdit = new()
            {
                Text = "编辑话术",
                Owner = this.FindForm(),
                Script = item.Tag as LanguageScript
            };

            if (frmLanguageScriptEdit.ShowDialog() == DialogResult.OK)
            {
                if (frmLanguageScriptEdit.Script != null)
                {
                    item.Tag = frmLanguageScriptEdit.Script;
                    item.SubItems[1].Text = frmLanguageScriptEdit.Script.Type == LanguageScriptType.Audio ? "音频文件" : "合成语音";
                    item.SubItems[3].Text = frmLanguageScriptEdit.Script.Status == 0 ? "正常" : "禁用";
                    item.SubItems[4].Text = frmLanguageScriptEdit.Script.Content;
                    DataChanged?.Invoke(this, EventArgs.Empty);
                }
            }
        }

        private void AddItemByDir_Click(object? sender, EventArgs e)
        {
            if (this.Scripts == null)
            {
                if (string.IsNullOrEmpty(Description))
                    MessageBox.Show(this, $"请先设置话术集数据.", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                    MessageBox.Show(this, $"请先设置【{Description}】的话术集.", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            FolderBrowserDialog folderDialog = new()
            {
                // 设置对话框的标题
                Description = "请选择要加载的话术音频文件夹"
            };

            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                string selectedPath = folderDialog.SelectedPath;

                string[] files = Directory.GetFiles(selectedPath);

                foreach (string file in files)
                {
                    string extension = Path.GetExtension(file);
                    if (extension.Contains("mp3") || extension.Contains("wav"))
                    {
                        LanguageScript item = new LanguageScript
                        {
                            Type = LanguageScriptType.Audio,
                            Content = file,
                            Status = 0
                        };
                        this.Scripts?.Add(item);

                        ListViewItem lvi = this.Items.Add((this.Items.Count + 1).ToString());
                        lvi.Tag = item;
                        lvi.SubItems.Add(item.Type == LanguageScriptType.Audio ? "音频文件" : "合成语音");
                        lvi.SubItems.Add(item.Status == 0 ? "正常" : "禁用");
                        lvi.SubItems.Add(item.Content);
                    }
                }
                DataChanged?.Invoke(this, EventArgs.Empty);
            }
        }

        private void DelItems_Click(object? sender, EventArgs e)
        {
            if (this.SelectedItems.Count < 1) return;

            if (MessageBox.Show(this, $"是否删除选中的话术?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (this.SelectedItems.Count > 0)
                {
                    List<LanguageScript> removeData = [];
                    foreach (var item in this.SelectedItems)
                    {
                        if (((ListViewItem)item).Tag is LanguageScript data)
                        {
                            removeData.Add(data);
                            this.Items.Remove((ListViewItem)item);
                            Scripts?.Remove(data);
                        }
                    }

                    for (int i = 0; i < this.Items.Count; i++)
                    {
                        this.Items[i].SubItems[0].Text = (i + 1).ToString();
                    }

                    DataChanged?.Invoke(this, EventArgs.Empty);
                }
            }
        }

        private void ClearItems_Click(object? sender, EventArgs e)
        {
            if (this.Items.Count < 1) return;

            if (MessageBox.Show(this, $"是否清空话术?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                this.Items.Clear();
                Scripts?.Clear();
                DataChanged?.Invoke(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// 清除话术内容(本方法不删除话术)
        /// </summary>
        public void UIClearScripts()
        {
            SceneId = null;
            this.Items.Clear();
            Scripts?.Clear();
            Scripts = null;
            this.Description = string.Empty;
        }

        protected override void OnDoubleClick(EventArgs e)
        {
            if (this.SelectedItems.Count < 1) return;

            ListViewItem item = this.SelectedItems[0];
            if (item == null || item.Tag == null) return;

            FrmLanguageScriptEdit frmLanguageScriptEdit = new()
            {
                Text = "编辑话术",
                Owner = this.FindForm(),
                Script = item.Tag as LanguageScript
            };
            if (frmLanguageScriptEdit.ShowDialog() == DialogResult.OK)
            {
                if (frmLanguageScriptEdit.Script != null)
                {
                    item.Tag = frmLanguageScriptEdit.Script;
                    item.SubItems[1].Text = frmLanguageScriptEdit.Script.Type == LanguageScriptType.Audio ? "音频文件" : "合成语音";
                    item.SubItems[3].Text = frmLanguageScriptEdit.Script.Status == 0 ? "正常" : "禁用";
                    item.SubItems[4].Text = frmLanguageScriptEdit.Script.Content;
                }
            }

            //base.OnDoubleClick(e);
        }
    }
}
